package main

import "fmt"

func main() {
	//例1 channel 通道
	//ch := make(chan string)
	//go func() {
	//	fmt.Println("Sending message...")
	//	ch <- "hello world!"
	//	fmt.Println("Message sent")
	//}()
	//
	//msg := <-ch
	//fmt.Println("received message:", msg)

	//例2  range遍历 和 通道关闭 close
	//ch := make(chan int)
	//go func() {
	//	for i := 0; i < 5; i++ {
	//		ch <- i
	//		time.Sleep(time.Second)
	//	}
	//	close(ch)
	//}()
	//
	//for x := range ch {
	//	fmt.Println("Received:", x)
	//}
	//
	//fmt.Println("Done!")

	//例3 多通道查询select 语句/通道的多路复用
	//ch1 := make(chan int)
	//ch2 := make(chan string)
	//
	//go func() {
	//	for i := 0; i < 5; i++ {
	//		ch1 <- i
	//		time.Sleep(time.Second)
	//	}
	//}()
	//go func() {
	//	for i := 0; i < 5; i++ {
	//		ch2 <- fmt.Sprintf("message %d", i)
	//		time.Sleep(time.Second)
	//	}
	//}()
	//
	//for i := 0; i < 10; i++ {
	//	select {
	//	case x := <-ch1:
	//		fmt.Println("Received from ch1:", x)
	//	case x := <-ch2:
	//		fmt.Println("Received from ch2:", x)
	//	}
	//}

	//例4 select 非阻塞查询

	//ch := make(chan int)
	//go func() {
	//	time.Sleep(time.Second * 3)
	//	close(ch)
	//}()
	//
	//for {
	//	select {
	//	case x, ok := <-ch:
	//		if !ok {
	//			fmt.Println("channel closed")
	//			return
	//		}
	//		fmt.Println("Received:", x)
	//	default:
	//		fmt.Println("no data received")
	//		time.Sleep(time.Second)
	//	}
	//}

	//例子5 带缓冲的通道
	ch := make(chan int, capacity)
	done := make(chan bool)
	//生产者
	go func() {
		for i := 0; i < capacity*2; i++ {
			ch <- i
			fmt.Println("produce:", i)

		}
		done <- true
	}()

	//消费者
	go func() {
		for i := 0; i < capacity*2; i++ {
			item := <-ch
			fmt.Println("consume:", item)
		}
		done <- true
	}()

	<-done
	<-done

}

const capacity = 5
